/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jsonHelper.SimpleConnection;
import service.Connection;
import service.ConnectionFacadeREST;
import service.Planet;
import service.PlanetFacadeREST;
import service.Universe;
import service.UniverseFacadeREST;

/**
 *
 * @author andrew
 */
public class connectionsServlet extends HttpServlet {

    @EJB
    private PlanetFacadeREST planetManager;
    @EJB
    private UniverseFacadeREST universeManager;
    
    @EJB 
    private ConnectionFacadeREST connectionManager;

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //HttpSession session = request.getSession();

        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist mettendo false
//        if(session != null && !session.isNew()) {} 
//        else {
//            response.sendRedirect("/home.jsp");
//        }

        Integer editingUniverseId = (Integer) session.getAttribute("idUniverse");


        PrintWriter out = response.getWriter();
        Gson gson = new Gson();
        ArrayList<SimpleConnection> arraySimpleConnection = new ArrayList<SimpleConnection>();

        // prendo ogni pianeta dell'universo ed estraggo le sue  connessioni
        Universe currentUniverse = universeManager.find(editingUniverseId);

        Collection<Planet> collPlanet = currentUniverse.getPlanetCollection();

        Iterator iteratorPlanet = collPlanet.iterator();
        while (iteratorPlanet.hasNext()) {
            Planet currentPlanet = (Planet) iteratorPlanet.next();

            // prendo la collezione di connessioni associata
            Collection<Connection> collConn = currentPlanet.getConnectionCollection();

            Iterator itConn = collConn.iterator();
            while (itConn.hasNext()) {
                Connection c = (Connection) itConn.next();
                SimpleConnection sc = new SimpleConnection();

                sc.setIdConnection(c.getIdConnection());
                sc.setStartPlanet(c.getPlanetidPlanet().getIdPlanet());
                sc.setDestinationPlanet(c.getDestinationPlanet());
                sc.setR(c.getR());
                sc.setG(c.getG());
                sc.setB(c.getB());

                arraySimpleConnection.add(sc);

                System.out.println("Pianeta destinazione: " + c.getDestinationPlanet());
            }

        }
    
        ArrayList<SimpleConnection> array = new ArrayList<SimpleConnection>();
        
        Iterator<SimpleConnection> itSimpleConn = arraySimpleConnection.iterator();
        while(itSimpleConn.hasNext()){
            SimpleConnection conn = itSimpleConn.next();
                        
            if( (!array.contains(conn))){
                // se la connessione non è sul set allora aggiungila
                array.add(conn);
            }
        }
        
//        Iterator<SimpleConnection> iter = array.iterator();
//        while(iter.hasNext()){
//            SimpleConnection s = iter.next();
//            System.out.println("Connessione "+s.getIdConnection() +", start: "+s.getStartPlanet()+", end: "+s.getDestinationPlanet());
//            
//        }
        
        String arrayGson = gson.toJson(array);
        out.println(arrayGson);
        out.close();

    }

    
    
    
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //HttpSession session = request.getSession();
        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {} 
//        else {
//            response.sendRedirect("/home.jsp");
//        }

        // predno ID universo dalla sesion
        Integer editingUniverseId = (Integer) session.getAttribute("idUniverse");

        Universe currentUniverse;

        // se ci sono i parametri X e Y alora sto spostando un pianeta, altrimenti devo aggiungere la connessione
        if ((request.getParameter("setX") != null) && (request.getParameter("setY") != null)) {
            // prendo pianeta arrivo
            String idPlanetMovedString = request.getParameter("planetMoved");
            int idPlanetMoved = Integer.parseInt(idPlanetMovedString);
            String setXString = request.getParameter("setX");
            int paramX = Integer.parseInt(setXString);
            String setYString = request.getParameter("setY");
            int paramY = Integer.parseInt(setYString);

            currentUniverse = universeManager.find(editingUniverseId);
            // prendo i suoi pianeti associati
            Collection<Planet> collPlanet = currentUniverse.getPlanetCollection();
            // cerco il pianeta di start nella collezione
            Iterator iteratorPlanet = collPlanet.iterator();
            while (iteratorPlanet.hasNext()) {
                Planet currentPlanet = (Planet) iteratorPlanet.next();
                if (currentPlanet.getIdPlanet() == idPlanetMoved) {
                    currentPlanet.setCoordinatePositionX(paramX);
                    currentPlanet.setCoordinatePositionY(paramY);
                    planetManager.edit(currentPlanet);
                }
            }

        } else {

            // prendo valore che determina l'azione da intraprendere
            String actionToDo = request.getParameter("actionToDo");

            // prendo pianeta partenza
            String idStartPlanetString = request.getParameter("startPlanet");
            int idStartPlanet = Integer.parseInt(idStartPlanetString);

            // prendo pianeta arrivo
            String idEndPlanetString = request.getParameter("endPlanet");
            int idEndPlanet = Integer.parseInt(idEndPlanetString);

            // determina se deve essere fatto un inserimento o una cancellazione
            if (actionToDo.equals("insert")) {
                // INSERIMENTO CONNESSIONE

                // prendo colore
                // r
                String rString = request.getParameter("red");
                int r = Integer.parseInt(rString);
                // g
                String gString = request.getParameter("green");
                int g = Integer.parseInt(gString);
                // b
                String bString = request.getParameter("blue");
                int b = Integer.parseInt(bString);

                // --- diretta ---

                // prendo un determinato universo
                currentUniverse = universeManager.find(editingUniverseId);
                // prendo i suoi pianeti associati
                Collection<Planet> collPlanet = currentUniverse.getPlanetCollection();

                // cerco il pianeta di start nella collezione
                Iterator iteratorPlanet = collPlanet.iterator();
                while (iteratorPlanet.hasNext()) {
                    Planet currentPlanet = (Planet) iteratorPlanet.next();
                    // se pianeta corrente è uguale a quello di partenza prendo le sue connessioni
                    if (currentPlanet.getIdPlanet() == idStartPlanet) {
                        Collection<Connection> collConn = currentPlanet.getConnectionCollection();

                        // gli aggiungo la nuova connessione
                        Connection newConnection = new Connection();
                        newConnection.setDestinationPlanet(idEndPlanet);
                        newConnection.setPlanetidPlanet(currentPlanet);
                        newConnection.setR(r);
                        newConnection.setG(g);
                        newConnection.setB(b);

                        collConn.add(newConnection);

                        currentPlanet.setConnectionCollection(collConn);

                        // aggiorno in db
                        planetManager.edit(currentPlanet);
                    }

                }

                // --- inversa ---

                // prendo un determinato universo
//                currentUniverse = universeManager.find(idEndPlanet);
                // prendo i suoi pianeti associati
//                collPlanet = currentUniverse.getPlanetCollection();
                // cerco il pianeta di start nella collezione
                iteratorPlanet = collPlanet.iterator();
                while (iteratorPlanet.hasNext()) {
                    Planet currentPlanet = (Planet) iteratorPlanet.next();
                    // se pianeta corrente è uguale a quello di partenza prendo le sue connessioni
                    if (currentPlanet.getIdPlanet() == idEndPlanet) {
                        Collection<Connection> collConn = currentPlanet.getConnectionCollection();

                        // gli aggiungo la nuova connessione
                        Connection newConnection = new Connection();
                        newConnection.setDestinationPlanet(idStartPlanet);
                        newConnection.setPlanetidPlanet(currentPlanet);
                        newConnection.setR(r);
                        newConnection.setG(g);
                        newConnection.setB(b);

                        collConn.add(newConnection);

                        currentPlanet.setConnectionCollection(collConn);

                        // aggiorno in db
                        planetManager.edit(currentPlanet);
                    }

                }

            } else {
                // CANCELLAZIONE CONNESSIONE
                System.out.println("CANCIELLOOOOOO");
                // prendo idConnessione da cancellare
//                String idConnectionToDeleteString = request.getParameter("idConnectionDelete");
//                int idConnectionToDelete = Integer.parseInt(idConnectionToDeleteString);

                // --- diretta ---

                // prendo un determinato universo
                currentUniverse = universeManager.find(editingUniverseId);
                // prendo i suoi pianeti associati
                Collection<Planet> collPlanet = currentUniverse.getPlanetCollection();

                // cerco il pianeta di start nella collezione
                Iterator iteratorPlanet = collPlanet.iterator();
                while (iteratorPlanet.hasNext()) {
                    Planet currentPlanet1 = (Planet) iteratorPlanet.next();
                    // se pianeta corrente è uguale a quello di partenza prendo le sue connessioni
                    if (currentPlanet1.getIdPlanet() == idStartPlanet) {
                        Collection<Connection> collConn = currentPlanet1.getConnectionCollection();

                        Iterator iteratorConnection = collConn.iterator();
                        while (iteratorConnection.hasNext()) {
                            Connection currentConnection = (Connection) iteratorConnection.next();
                            if (currentConnection.getDestinationPlanet() == idEndPlanet) {
                                iteratorConnection.remove();
                                connectionManager.remove(currentConnection);
                                
                            }
                        }

                        // aggiorno la collezione di connessioni presenti
                        currentPlanet1.setConnectionCollection(collConn);

                        // aggiorno in db
                        planetManager.edit(currentPlanet1);
                    }

                }



                // --- inversa ---
                // prendo un determinato universo
//                currentUniverse = universeManager.find(idEndPlanet);
                // prendo i suoi pianeti associati
//                collPlanet = currentUniverse.getPlanetCollection();

                // cerco il pianeta di start nella collezione
                iteratorPlanet = collPlanet.iterator();
                while (iteratorPlanet.hasNext()) {
                    Planet currentPlanet2 = (Planet) iteratorPlanet.next();
                    // se pianeta corrente è uguale a quello di partenza prendo le sue connessioni
                    if (currentPlanet2.getIdPlanet() == idEndPlanet) {
                        Collection<Connection> collConn = currentPlanet2.getConnectionCollection();

                        Iterator iteratorConnection = collConn.iterator();
                        while (iteratorConnection.hasNext()) {
                            Connection currentConnection = (Connection) iteratorConnection.next();
                            if (currentConnection.getDestinationPlanet() == idStartPlanet) {
                                iteratorConnection.remove();
                                connectionManager.remove(currentConnection);
                            }
                        }

                        // aggiorno la collezione di connessioni presenti
                        currentPlanet2.setConnectionCollection(collConn);

                        // aggiorno in db
                        planetManager.edit(currentPlanet2);
                    }

                }

            }
        }

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
